<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 顶层添加组件 -->
        <PageTool ref="PageTool" :btn-name="'客户'" @addEvent="addEvent" @searchEvent="searchEvent">
          <template v-slot:right>
            <el-dropdown trigger="click" @command="dropdownItem">
              <el-button>
                {{ allItem }}<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="全部客户">全部客户</el-dropdown-item>
                <el-dropdown-item command="全部经纪人">全部经纪人</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </PageTool>
        <!-- 底部信息栏的展示 -->
        <el-table :data="clientsList" border>
          <el-table-column label="图片">
            <template v-slot="{row}">
              <img v-imgerror="require('@/assets/common/bigUserHeader.png')" :src="row.image" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="phone" label="电话" />
          <el-table-column prop="agent.name" label="经纪" />
          <el-table-column prop="wechat" label="微信" />
          <el-table-column prop="desc" label="介绍" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button size="small" type="primary" @click="editClient(row.id)">编辑</el-button>
              <el-button size="small" @click="delClientFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="displayPagination" class="block">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pazeSize._limit"
            :total="total"
            :current-page="pageSize"
            @current-change="pazeSizeFn"
          />
        </div>
      </el-card>

      <!-- 编辑信息弹出框 -->
      <el-dialog :title="userList.id? '编辑客户':'新增客户'" :visible="dialogFormVisible" @close="closeFn">
        <el-form ref="form" :model="userList" :rules="rules">
          <el-form-item label="经纪" label-width="50px">
            <el-select v-model="agentsList" placeholder="请选择经济人">
              <el-option v-for="(item,index) in agentsLists" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" label-width="50px" prop="name">
            <el-input v-model="userList.name" />
          </el-form-item>
          <el-form-item label="邮箱" label-width="50px" prop="email">
            <el-input v-model="userList.email" />
          </el-form-item>
          <el-form-item label="电话" label-width="50px" prop="phone">
            <el-input v-model="userList.phone" />
          </el-form-item>
          <el-form-item label="微信" label-width="50px" prop="wechat">
            <el-input v-model="userList.wechat" />
          </el-form-item>
          <el-form-item label="描述" label-width="50px" prop="desc">
            <el-input v-model="userList.desc" />
          </el-form-item>
          <el-form-item label="封面" label-width="50px">
            <!-- 选择框 -->
            <!-- <el-upload
              action="#"
              list-type="picture-card"
              :http-request="uploadFn"
              :file-list="fileList"
              :limit="1"
              :on-change="fileSuccess"
            >
              <i class="el-icon-plus" />
            </el-upload> -->
            <ImageUpload ref="imageUpload" :img-type="'image'" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="btnFn">确 定</el-button>
          <el-button @click="closeFn">取 消</el-button>
        </div>

      </el-dialog>

    </div>
  </div>
</template>

<script>

import { getClients, getClientsDetail, editClientsDetail, addClients, getClientCount, delClientsDetail } from '@/api/client.js'
import { getAgents } from '@/api/agents.js'
export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (value && !reg.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    return {
      allItem: '全部客户', // 全部客户和全部经纪人的切换
      displayPagination: true, // 分页组件的销毁和显示，使用在新增数据后跳转到下一个页面
      clientsList: [], // 客户列表
      // 客户列表，每页显示条数
      total: null, // 总的数据量
      pageSize: null, // 请求的页数
      pazeSize: {
        _limit: 5,
        _start: 0
      },
      userList: {
        agent: null,
        name: '',
        email: '',
        phone: '',
        wechat: '',
        desc: '',
        image: ''
      }, // 客户详情数据列表
      dialogFormVisible: false, // 显示弹框
      fileList: [],
      agentsList: '',
      agentsLists: [], // 获取经纪员列表
      rules: {
        // agent: [
        //   { required: true, message: '必需选择经纪人', trigger: 'change' }
        // ],
        name: [
          { required: true, message: '名字不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkEmail, message: '邮箱地址错误', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' }
        ],
        wechat: [
          { required: true, message: '微信不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
      // 分页显示

    }
  },
  async created() {
    this.getClients()
  },
  methods: {
    // 搜索按钮
    async searchEvent() {
      // console.log(this.$refs.PageTool.searchKey)
      const searchItem = this.$refs.PageTool.searchKey

      this.$nextTick(async() => {
        if (this.allItem === '全部客户') {
          this.displayPagination = false
          if (!searchItem) {
            this.displayPagination = true
          }
          // 搜索数据
          const res = await getClients({ name_contains: searchItem })
          // console.log(res)
          this.clientsList = res.data
          return
        }

        if (this.allItem === '全部经纪人') {
          this.displayPagination = false
          // 如果搜索值是空的，则直接获取全部数据就好，不执行查询
          if (!searchItem) {
            this.displayPagination = true
            return this.getClients()
          }
          const aaa = this.agentsLists.filter(item => item.name === searchItem)
          // console.log(aaa)
          // 搜索数据
          const res = await getClients({ agent: aaa[0].id })
          // console.log(res)
          this.clientsList = res.data
          return
        }
      })
    },
    // 下拉按钮触发事件
    dropdownItem(val) {
      // console.log(obj)
      this.allItem = val
    },
    // 改变页数
    pazeSizeFn(page) {
      // console.log(page)
      this.pageSize = page
      this.pazeSize._start = (page - 1) * this.pazeSize._limit
      this.getClients()
    },
    // 获取列表数据
    async getClients() {
      // 获取所有的客户条数
      const ress = await getClientCount()
      // console.log(res)
      this.total = ress.data

      // 获取用户数据
      // const res = await getClients({ _limit: 2, _start: 0 })
      const res = await getClients(this.pazeSize)
      // console.log(38, res)
      this.clientsList = res.data
      // 获取经纪人列表
      const result = await getAgents()
      // console.log(result)
      this.agentsLists = result.data
    },
    // 编辑按钮获取数据
    async editClient(id) {
      const res = await getClientsDetail(id)
      // console.log(res)
      this.userList = res.data
      this.agentsList = res.data.agent ? res.data.agent.id : ''
      this.dialogFormVisible = true

      // 回显图片数据到组件
      // console.log(this.$refs.imageUpload)
      this.$nextTick(() => {
        this.$refs.imageUpload.fileList[0] ? '' : this.$refs.imageUpload.fileList.push({ url: res.data.image })
      })
    },
    // 弹出新增提示框
    addEvent() {
      this.dialogFormVisible = true
    },
    // 数据提交
    async btnFn() {
      await this.$refs.form.validate()
      const image = this.$refs.imageUpload.fileList[0] ? this.$refs.imageUpload.fileList[0].url : ''
      if (!this.agentsList) {
        return this.$message.error('必须选择经纪人')
      }
      if (!image) {
        return this.$message.error('必须上传头像')
      }
      // console.log(image)
      // console.log(this.agentsList)
      if (this.userList.id) {
        await editClientsDetail({
          ...this.userList,
          agent: this.agentsList,
          image
        })
      } else {
        // console.log(1)
        // console.log({
        //   ...this.userList,
        //   agent: this.agentsList,
        //   image
        // })
        // 判断如果添加的数据超过要获取的数据，我们就获取新的页面
        if (this.clientsList.length === this.pazeSize._limit) {
          this.pageSize = this.pageSize + 1
          this.pazeSize._start = (this.pageSize - 1) * this.pazeSize._limit
          this.displayPagination = false
        }
        await addClients({
          ...this.userList,
          agent: this.agentsList,
          image
        })
      }
      // console.log(res)
      this.displayPagination = true
      // 编辑成功后关闭弹窗，渲染数据
      this.getClients()
      this.closeFn()
    },

    // 关闭弹窗
    closeFn() {
      this.dialogFormVisible = false
      // console.log(this.userList.agent)
      // 取消的时候都清空一下客户信息
      this.userList = {}
      this.$refs.imageUpload.fileList = []
      // console.log(1)
      // console.log(this.agentsList)
    },
    // 删除数据
    delClientFn(id) {
      // 二次确认是否删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delClientsDetail(id)
        this.clientsList.pop()
        if (this.clientsList.length < 1 && this.pageSize > 1) {
          this.pageSize = this.pageSize - 1
          // console.log(1)
          this.pazeSize._start = (this.pageSize - 1) * this.pazeSize._limit
        }
        this.$nextTick(() => {
          this.getClients()
        })
        this.$message({
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除'
        })
      })
    }

  }

}
</script>

<style lang='scss' scoped>
  img{
    width: 100%;
  }
  .block{
    text-align: center;
    margin:20px 0 15px
  }
</style>
